/**
 * @module  首页
 * @author xiongsha
 * @date 2020-12-21 21:31:01
 */

import React, { useState, useEffect } from 'react';
import HeaderComponent from '@src/pages/components/Header';
import { Tabs, Toast } from 'antd-mobile';
import request from '@src/utils/request';
import { RouteComponentProps, withRouter } from 'react-router';
import moment from 'moment';
import './index.less';
import { Link } from 'react-router-dom';

interface IDetail {
  address?: string;
  phone?: string;
}

interface ITabItem {
  title?: string;
  key?: number;
  image?: string;
  content?: string;
}

const Home: React.FC<RouteComponentProps> = (props: RouteComponentProps) => {
  const [tabs, setTab] = useState([]);
  const [detail, setDetail] = useState<IDetail>({});
  const [date, setDate] = useState<string[]>([]);
  const [tabItem, setTabItem] = useState<ITabItem>({});
  const getTab = () => {
    // 获取tab列表
    request('get', '/api/v1/venues').then((res) => {
      if (res && res.code === 200) {
        const { data } = res;
        const tabList = data.map((cur) => {
          return {
            title: cur.name,
            key: cur.id,
            image: cur.image,
            content: cur.content,
          };
        });
        setTabItem(tabList[0]);
        setTab(tabList);
      } else {
        Toast.fail(res.message);
      }
    });
  };
  const getUser = (key, time) => {
    request('get', '/api/v1/user').then((res) => {
      if (res && res.code === 200) {
        const { data } = res;
        if (!data.bound_phone) {
          props.history.replace('/login');
        } else {
          props.history.push(`/appointment/${key}/${time}`);
        }
      } else {
        Toast.fail(res.message);
      }
    });
  };

  const getCode = (key, time) => {
    // 获取微信code
    // http://tianrui.vic0922.top/api/v1/socials/oauth
    const openid = localStorage.getItem('openid');
    const token = localStorage.getItem('token');
    if (openid && token) {
      // 如果有openid且有token
      getUser(key, time);
      return;
    }
    let { search } = location;
    let seaechArr = search.split('&');
    seaechArr = seaechArr[0].split('=');
    const code = seaechArr[1];
    if (!openid && !code) {
      location.href =
        'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9f0af8e61b261be9&redirect_uri=http%3a%2f%2ftianrui.vic0922.top%2f&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
    }
    request('post', '/api/v1/socials/authorizations', {
      code: openid ? undefined : code,
      openid,
    }).then((res) => {
      if (res && res.code === 200) {
        localStorage.setItem('token', res.data.access_token);
        localStorage.setItem('openid', res.data.openid);
        localStorage.setItem('time', res.data.expiration);
        getUser(key, time);
      }
    });
  };

  const getDetail = () => {
    request('get', '/api/v1/index').then((res) => {
      if (res && res.code === 200) {
        setDetail(res.data);
      }
    });
  };

  const getDate = () => {
    // 获取预定时间
    const date: string[] = [];
    for (let i = 0; i < 3; i++) {
      const day = moment().add('days', i).format('YYYY-MM-DD');
      date.push(day);
    }
    setDate(date);
  };

  useEffect(() => {
    getDate();
    getDetail();
    getTab();
  }, []);

  const renderContent = (tab) => (
    <ul className="main-ul">
      {date.map((cur) => (
        <li className="main-list" key={cur}>
          <span className="label">{cur}</span>
          <span className="text-btn" onClick={() => getCode(tab.key, cur)}>
            预定
          </span>
        </li>
      ))}
    </ul>
  );
  const changeTabName = (tab) => {
    setTabItem(tab);
  };

  return (
    <div className="main-home">
      <HeaderComponent text="场馆详情" />
      <div className="home-header">
        <img className="home-img" src={tabItem.image} alt="" />
        <div className="home-right">
          <p>{tabItem.title}</p>
        </div>
      </div>
      <div className="main-content">{tabItem.content}</div>
      <Tabs
        onTabClick={changeTabName}
        tabs={tabs}
        renderTabBar={(props) => {
          return <Tabs.DefaultTabBar {...props} page={3} />;
        }}
      >
        {renderContent}
      </Tabs>
      <ul className="my-ul">
        <li className="my-list">
          <img className="icon-img" src={require('@src/img/icon-recharge.png')} alt="" />
          充值活动
          <Link to="/recharge" className="go-link">
            去看看
          </Link>
        </li>
        <li className="my-list">
          <img className="icon-img" src={require('@src/img/icon-recharge.png')} alt="" />
          会员卡办理
          <Link to="/vip" className="go-link">
            去办理
          </Link>
        </li>
        <li className="my-list">
          <img className="icon-img" src={require('@src/img/icon-phone.png')} alt="" />
          {detail.phone}
        </li>
        <li className="my-list">
          <img className="icon-img" src={require('@src/img/icon-location.png')} alt="" />
          {detail.address}
        </li>
      </ul>
    </div>
  );
};

export default withRouter(Home);
